#!/usr/bin/perl -w  # useful for syntax highlighting
package clreqd_modules;

# This has been modified to check the name to restore from
# and make the following decisions:
# .Z - the configuration is compressed, so uncompress it
# .gz - the configuration is gzipped, so gunzip it
# .bz2 - the configuration is bzip2ed, so bunzip2 it

use File::Basename;

sub config_restore {
my %ARGS=@_;
my ($file,$what);

	local $SIG{CHLD}='DEFAULT';
	$file=$ARGS{FILE};
	$what=$ARGS{WHAT};
	if(! -e $file) {
		return "FAIL File '$file' does not exist.";
	}
	if(! -f $file) {
		return "FAIL '$file' is not a regular file.";
	}
	# Check that what is
	if($what !~ /^(DB|KEYS|CFG|ALL)$/i) {
		return "FAIL 'What' value is not 'DB','KEYS','CFG' or 'ALL'.";
	}

	# Initially do a tar tf to check it is a tar file, and look 
	# for 

	my ($tar,$fd,$cline,$gunzip,$uncompress,$bunzip2);
	if(-x "/bin/tar") {
		$tar="/bin/tar";
	} else {
		$tar="/usr/bin/tar";
	}
	my $cat="/usr/bin/cat";
	$cat="/bin/cat" if -x "/bin/cat";

	my @DD=("/usr/bin","/bin","/usr/local/bin","/usr/contrib/bin");
	my %uncompress_cmds=();
	for my $pp ("gunzip","uncompress","bunzip2") {
		for my $cdir (@DD) {
			if(-x "$cdir/$pp") {
				$uncompress_cmds{"$pp"}="$cdir/$pp";
				last;
			}
		}
	}
	$comp_command="";
	$comp_type=undef;
	if($file =~ /\.Z$/) {
		$comp_type="uncompress";
	} elsif($file =~ /\.gz$/) {
		$comp_type="gunzip";
	} elsif($file =~ /\bz2z$/) {
		$comp_type="bunzip2";
	}
	if(defined($comp_type)) {
		if(!exists($uncompress_cmds{$comp_type})) {
			return "FAIL Utility to uncompress file ['$comp_type'] not found.";
		}
		$comp_command="$uncompress_cmds{$comp_type} -c $file";
	} else {
		$comp_command="$cat $file";
	}
	open($fd,"$comp_command | $tar tf -|");
	my $ok=0;
	while($cline=<$fd>) {
		chomp $cline;
		if($cline eq "./VERSION") {
			$ok=1;
		}
	}
	close($fd);
	if(!$ok) {
		return "FAIL File '$file' is not in expected format.";
	}

	#################################################################
	# Handle the tar extracts...					#
	#################################################################
	if(lc($what) eq "db") {
		system("cd $::ENV{TRUECL_CFG}; $comp_command | $tar xf - ./config.db ./status.db >/dev/null 2>/dev/null");
	} elsif(lc($what) eq "keys") {
		system("cd $::ENV{TRUECL_CFG}; $comp_command | $tar xf - ./keys ./pki >/dev/null 2>/dev/null");
	} elsif(lc($what) eq "cfg") {
		system("cd $::ENV{TRUECL_CFG}; $comp_command | $tar xf - ./clreqd.xml ./clreqd_cmds.xml ./topology.xml ./master-defaults.xml ./topology.xml ./skulker2-rules-truecl.xml ./clreqd-svc.xml >/dev/null 2>/dev/null");
	} else {
		system("cd $::ENV{TRUECL_CFG}; $comp_command | $tar xf - >/dev/null 2>/dev/null");
	}
	if($?>>8) {
		return "FAIL Unable to extract files from '$file' using '$comp_command | $tar xf -'.";
	}
	return "OK";
}

1;
